﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace blackhouse.Payments {
    /// <summary>
    /// Summary description for PaymentOnline
    /// </summary>
    public class PaymentOnline : IHttpHandler {

        #region Fields

        private int posId;
        private string sessionId;
        private string ts;
        private string sig;

        private HttpContext context;

        private PayUConfig config;
        private PaymentTransaction transaction;
        private RemoteUpdatePaymentTransaction remoteTransaction;

        #endregion

        #region IHttpHandler Members

        public void ProcessRequest(HttpContext context) {
            this.context = context;

            context.Response.ContentType = "text/plain";

            // Zidentyfikowanie transakcji
            // Sprawdzenie podpisu
            // Pobranie i zaktualizowanie transakcji
            // Wywołanie rozszerzeń 
            // Odpowiedź OK
            this.ReadInputParameters();
            this.SetInstance();
            if (!this.CheckSignifaction()) {
                context.Response.Write("Błędna wartość podpisu. Otrzymany klucz to:" + this.sig);
                return;
            }

            try {
                this.remoteTransaction.UpdateFromService();
            }
            catch (Exception e) {
                context.Response.Write(e.Message + Environment.NewLine + e.StackTrace);
                return;
            }

            context.Response.Write("OK");
        }

        public bool IsReusable {
            get {
                return false;
            }
        }

        #endregion

        #region Methods

        private void ReadInputParameters() {
            Int32.TryParse(this.context.Request["pos_id"], out this.posId);
            this.sessionId = this.context.Request["session_id"];
            this.ts = this.context.Request["ts"];
            this.sig = this.context.Request["sig"];
        }

        private bool CheckSignifaction() {
            string s = this.posId + this.sessionId + ts + this.config.KeyIn;
            return s.GetMd5().ReplaceEx("-", "").Equals(this.sig, StringComparison.InvariantCultureIgnoreCase);
        }

        private void SetInstance() {
            this.config = PayUConfig.Get();
            this.transaction = PaymentTransaction.Find(posId, sessionId);
            this.remoteTransaction = new RemoteUpdatePaymentTransaction(this.transaction);
        }

        #endregion

    }
}